// 1.引入基础模块
const express = require("express");
const { find, addOne, editOne, reomveOne } = require("../models/db");
// 2.获取路由实例
const router = express.Router();

// 查询good表中的数据
// "_id": "66938838175ff630ab417484",
// "shopName": "小米手机",
// "imgUrl": "https://gw.alicdn.com/imgextra/i1/2206588314948/O1CN01Z8ZcuT1mQEh6IygGB_!!2206588314948-0-C2M.jpg_Q75.jpg_.webp",
// "shopInfo": "不错的手机",
// "shopPrice": "2000",
// "shopSelect": "v1"
router.get("/ceshidb", async function (req, res) {
  let result = await find(
    "good",
    { shopName: "小米手机" },
    {
      // projection: {
      _id: 0,
      shopName: 1,
      imgUrl: 1,
      shopInfo: 0,
      shopPrice: 0,
      shopSelect: 0,
      // },
    }
  );
  res.send({ code: 200, msg: "数据查询成功", data: result });
});

// 新增数据
router.get("/addRow", async function (req, res) {
  // 模拟新增的数据，后期需要客户端传递过来
  let insertData = {
    shopName: "小米手机" + Math.ceil(Math.random()),
    imgUrl:
      "https://gw.alicdn.com/imgextra/i1/2206588314948/O1CN01Z8ZcuT1mQEh6IygGB_!!2206588314948-0-C2M.jpg_Q75.jpg_.webp",
    shopInfo: "5C认证的手机",
    shopPrice: "4500",
    shopSelect: "v1",
  };
  try {
    let result = await addOne("good", insertData);
    console.log("新增数据返回结果是：", result);
    res.send({ code: 200, msg: "数据添加成功", data: [] });
  } catch (error) {
    console.log(error);
    res.send({ code: 501, msg: "数据添加失败", data: [] });
  }
});

// 修改数据
router.get("/editRow", async function (req, res) {
  // 模拟修改的数据条件
  let filter = { shopName: "小米手机" };
  // 模拟待修改的数据
  let updateDoc = { $set: { shopPrice: 999 } };
  try {
    let result = await editOne("good", filter, updateDoc);
    console.log("修改数据返回结果是：", result);
    res.send({ code: 200, msg: "数据修改成功", data: [] });
  } catch (error) {
    console.log(error);
    res.send({ code: 501, msg: "数据添加失败", data: [] });
  }
});

// 删除数据
router.get("/removeRow", async function (req, res) {
  // 模拟删除的数据条件
  let filter = { shopName: "苹果电脑" };
  try {
    let result = await reomveOne("good", filter);
    console.log("删除数据返回结果是：", result);
    res.send({ code: 200, msg: "数据删除成功", data: [] });
  } catch (error) {
    console.log(error);
    res.send({ code: 501, msg: "数据删除失败", data: [] });
  }
});

module.exports = router;

let obj = {
  find() {},
  connectDB() {},
};
